//
//  CommitsViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/27.
//


import UIKit
import MJRefresh
import PKHUD
import UITableView_FDTemplateLayoutCell
import BTNavigationDropdownMenu

/// 提交列表控制器
class CommitsViewController: BaseViewController {
    
    var commitsTableView:UITableView!
    var cellID = "commitscellid"
    var commitModelArray:[CommitModel]?
    var menu:BTNavigationDropdownMenu!
    var projectModel:ProjectMdoel!
    var currentPage = 1
    var branchName = "master"
    // 分支数组
    var branchNameArray:[String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupBranchDatas()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if menu != nil {
            if menu.isShown{
                menu.hide()
            }
        }
    }
    
    
    init(project: ProjectMdoel) {
        super.init(nibName: nil, bundle: nil)
        self.projectModel = project
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - 设置界面
extension CommitsViewController {
    
    func setupUI(){
        
        var fra = view.bounds
        fra.size.height -= Common.topHeight
        commitsTableView = UITableView(frame: fra)
        commitsTableView.register(UINib.init(nibName: "CommitTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        view.addSubview(commitsTableView)
        commitsTableView.delegate = self
        commitsTableView.dataSource = self
        commitsTableView.separatorStyle = .none
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        commitsTableView.mj_header = mjH
//        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        commitsTableView.mj_footer = mjF
        
        commitsTableView.emptyDataSetDelegate = self
        commitsTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            commitsTableView.backgroundColor = Colors.backgroundColor
        }
    }
    
    // 展示分支
    func setupBranch(){
        
        self.branchName = branchNameArray.first ?? "master"
        menu = BTNavigationDropdownMenu(title: BTTitle.index(0), items: branchNameArray)
        if #available(iOS 13.0, *) {
            menu.cellBackgroundColor = Colors.backgroundColor
            menu.cellTextLabelColor = Colors.labelColor
        } else {
            menu.cellBackgroundColor = .white
            menu.cellTextLabelColor = .darkGray
        }
        menu.cellSeparatorColor = Colors.BLUE_COLOR
        menu.didSelectItemAtIndexHandler = {[weak self] (indexPath: Int) -> () in
            self?.currentPage = 1
            self?.branchName = (self?.branchNameArray[indexPath])!
            self?.commitsTableView.mj_header.beginRefreshing()
        }
        
        self.navigationItem.titleView = menu
        self.commitsTableView.mj_header.beginRefreshing()
    }
}


extension CommitsViewController {
    
    // 加载提交文件信息
    func loadData(page: Int){
        
        let url = URLs.V3URL + URLs.PROJECTS + self.projectModel.id.description + "/repository/commits?ref_name=\(branchName)&page=\(self.currentPage)"
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[CommitModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.commitModelArray = result.data as? [CommitModel]
                    }else {
                        self.commitModelArray?.append(contentsOf: (result.data as? [CommitModel])!)
                        if result.data?.count == 0 {
                            self.commitsTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.commitsTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.commitsTableView.mj_header.endRefreshing()
                self.commitsTableView.mj_footer.endRefreshing()
            }
        }
    }
    
    // 获取分支数据
    func setupBranchDatas(){
        
        HUD.show(.progress)
        let group = DispatchGroup()
        let quene = DispatchQueue.global()
        
        quene.async(group: group, execute: {
            group.enter()
            
            let url = URLs.V3URL + URLs.PROJECTS + self.projectModel.id.description + "/repository/branches"
            // 异步加载
            DispatchQueue.global().async {
                let result:Result<[BranchTagModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
                DispatchQueue.main.async {
                    if result.code == 0 {
                        if let models = result.data {
                            for model in models {
                                self.branchNameArray.append(model!.name)
                            }
                        }
                    }else {
                        HUD.flash(.label(result.message), delay: 1.0)
                    }
                    
                    group.leave()
                }
            }
        })
        
        quene.async(group: group, execute: {
            group.enter()
            
            let url = URLs.V3URL + URLs.PROJECTS + self.projectModel.id.description + "/repository/tags"
            // 异步加载
            DispatchQueue.global().async {
                let result:Result<[BranchTagModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
                DispatchQueue.main.async {
                    if result.code == 0 {
                        if let models = result.data {
                            for model in models {
                                self.branchNameArray.append(model!.name)
                            }
                        }
                    }else {
                        HUD.flash(.label(result.message), delay: 1.0)
                    }
                    
                    group.leave()
                }
            }
        })
        
        group.notify(queue: quene) {
            DispatchQueue.main.async {
                HUD.hide()
                self.setupBranch()
            }
            
        }
    }
}


extension CommitsViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.commitModelArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.commitModelArray![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CommitTableViewCell
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! CommitTableViewCell).model = self.commitModelArray![indexPath.row]
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.commitModelArray![indexPath.row]
        let vc = CommitDeitalAndSubCommitViewController(model: model, project: self.projectModel!,titles: ["提交","评论"])
        vc.title = self.branchName
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
